package com.zxx.casserver.base.error;

import com.alibaba.fastjson.JSON;
import com.zxx.cascommon.base.result.Result;
import com.zxx.cascommon.base.result.ResultUtils;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * spring boot 底层异常处理统一类
 *
 * @author zhoukai
 * @date 2019/5/6 11:33
 */
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BaseErrorController implements ErrorController {

    private static final String PATH = "/error";

    private final ErrorAttributes errorAttributes;

    public BaseErrorController(ErrorAttributes errorAttributes) {
        this.errorAttributes = errorAttributes;
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }

    @RequestMapping
    @ResponseBody
    public Result doHandleError(HttpServletRequest request) {
        ServletWebRequest servletWebRequest = new ServletWebRequest(request);
        Map<String, Object> errorAttributesData = errorAttributes.getErrorAttributes(servletWebRequest, true);
        Integer status = (Integer) errorAttributesData.get("status");
        String path = (String) errorAttributesData.get("path");
        String messageFound = (String) errorAttributesData.get("message");
        Map<String, Object> msgMap = new HashMap<>(3);
        msgMap.put("status", status);
        msgMap.put("path_", path);
        msgMap.put("message", messageFound);
        return ResultUtils.fail(JSON.toJSONString(msgMap));
    }

}
